package com.sky.config.shiro;

import com.sky.domain.User;
import com.sky.service.UserService;
import com.sky.vo.ActiveUser;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

/**
 * 自定义realm去匹配用户名和密码
 * @author sky
 * @create 2020-10-31 14:04
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    @Lazy
    private UserService userService;

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    /**
     * 做认证  --就是登录
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //得到用户的登录名
        String phone = token.getPrincipal().toString();
        //根据电话查询用户是否存在
        User user = userService.queryUserByPhone(phone);
        if(null!=user) { //说明用户存在但密码可能不正确
            //组装存放在redis里面的对象
            ActiveUser activeUser = new ActiveUser();
            activeUser.setUser(user);
            //匹配密码
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                activeUser, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName()
            );
            return info;
        }else {
            return null;  //代表用户不存在
        }
    }

    /**
     * 做授权  --登录成功之后，判断用户是否有某个菜单或按钮的权限
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //身份得到的就是上一个方法 返回值的第一个参数 ActiveUser
        ActiveUser activeUser = (ActiveUser) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }
}
